package com.s7.widget.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseListAdapter<T> extends BaseAdapter {

    protected List<T> datas;

    public BaseListAdapter() {
         if (this.datas == null) {
             this.datas = new ArrayList<>();
         }
    }

    public BaseListAdapter(List<T> datas) {
        this.datas = datas;
    }

    @Override
    public int getCount() {
        return datas == null ? 0 : datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas == null ? null : datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {

        BaseViewHolder baseViewHolder = null;
        if(convertView == null){
            convertView = LayoutInflater.from(viewGroup.getContext()).inflate(bindLayoutId(), null);
            baseViewHolder = new BaseViewHolder(convertView);
            convertView.setTag(baseViewHolder);
        }
        baseViewHolder = (BaseViewHolder) convertView.getTag();

        T data;
        if(datas == null || datas.size() <= position){
            data = null;
        } else {
            data = datas.get(position);
        }

        initView(position, data, baseViewHolder);

        return convertView;
    }

    public void onRefresh(List<T> datas) {
        if (this.datas == null) {
            this.datas = new ArrayList<>();
        }
        this.datas.clear();
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    public void addData(List<T> datas) {
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    public void onReplace(int position, T data) {
        this.datas.set(position, data);
        notifyDataSetChanged();
    }

    public void onRemove(int position) {
        this.datas.remove(position);
        notifyDataSetChanged();
    }


    public List<T> getDatas() {
        return datas;
    }

    protected abstract int bindLayoutId();

    protected abstract void initView(int position, T data, BaseViewHolder viewHolder);

    public class BaseViewHolder {
        private Map<Integer, View> mViewMap;
        private View itemView;
        public BaseViewHolder(View itemView) {
            this.itemView = itemView;
            mViewMap = new HashMap<>();
        }

        public <T extends View> T getView(int id) {
            View view = mViewMap.get(id);
            if (view == null) {
                view = itemView.findViewById(id);
                mViewMap.put(id, view);
            }
            return (T) view;
        }
    }
}
